import 'dart:convert';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/commuity/MaterialCenter.dart';
import 'package:panda/commuity/PlayBill.dart';
import 'package:panda/commuity/StudyClass.dart';
import 'package:panda/entity/article_list_entity.dart';
import 'package:panda/entity/banner_entity.dart';
import 'package:panda/event/UserInfoEvent.dart';
import 'package:panda/goods_by_cat_list/SearchGoods.dart';
import 'package:panda/goods_by_cat_list/SelectTopGods.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/SignUtil.dart';
import 'package:panda/set/ArticleDetail.dart';

import '../base/Constant.dart';

class CommuityPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CommuityFragmentState();
  }
}

class CommuityFragmentState extends State<CommuityPage>
    with WidgetsBindingObserver {
  List<BannerModelData> bannerData;
  EasyRefreshController _controller = new EasyRefreshController();
  List<HomeListDataData> dataList = new List();
  String phone = "";
  int page = 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadBanner();
    loadList();
    APPLIC.eventBus.on<UserInfoEvent>().listen((event) {
      getString(TOKEN).then((value) {
        phone = APPLIC.userInfoMap['user_msg']['phone'];
        loadBanner();

        setState(() {});
      });
    });
  }

  loadList() async {
    Map map = new Map();
    map['cat_id'] = "6";
    map['p'] = page.toString();
    map['per'] = "10";
    map['sign_type'] = SignType.GET_ARTICLE_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GET_SYSTEM_ARTICLE, data: getSign(map));
    print(response.data);
    Map userMap = json.decode(response.data);
    HomeListEntity homeServiceEntity = new HomeListEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      if (page == 1) {
        dataList.clear();
        _controller.resetLoadState();
        _controller.finishRefresh();
      } else {
        _controller.finishLoad(
            noMore: homeServiceEntity.data.datas.length == 0);
        if (homeServiceEntity.data.datas.length == 0) {
          Fluttertoast.showToast(msg: "已经加载全部");
        }
      }
      dataList.addAll(homeServiceEntity.data.datas);
      setState(() {});
    }
  }

  Future loadBanner() async {
    Map map = new Map();
    map['cat_id'] = "1";
    map['sign_type'] = SignType.GET_BANNER_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GETBANNER, data: getSign(map));
    Map userMap = json.decode(response.data);
    BannerModelEntity bannerEntity = new BannerModelEntity.fromJson(userMap);
    setState(() {
      bannerData = bannerEntity.data;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: white,
      body: AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle.light,
        child: EasyRefresh(
          controller: _controller,
          enableControlFinishLoad: true,
          enableControlFinishRefresh: true,
          header: MaterialHeader(),
          footer: MaterialFooter(),
          onRefresh: () {
            page = 1;
            loadList();
          },
          onLoad: () {
            page++;
            loadList();
          },
          child: ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              if (index == 0) {
                return new Stack(
                  children: <Widget>[
                    Container(
                      width: double.infinity,
                      height:
                          ScreenUtil.getInstance().setHeight(DP_250 + DP_10),
                      decoration: BoxDecoration(color: mainColor),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(
                          0,
                          MediaQueryData.fromWindow(window).padding.top +
                              ScreenUtil.getInstance().setHeight(10),
                          0,
                          0),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Container(
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              child: Center(
                                child: new GestureDetector(
                                  child: Container(
                                    padding: EdgeInsets.fromLTRB(
                                        ScreenUtil.getInstance()
                                            .setHeight(DP_20),
                                        ScreenUtil.getInstance()
                                            .setWidth(DP_10),
                                        ScreenUtil.getInstance()
                                            .setHeight(DP_20),
                                        ScreenUtil.getInstance()
                                            .setWidth(DP_10)),
                                    margin: EdgeInsets.fromLTRB(
                                        ScreenUtil.getInstance()
                                            .setHeight(DP_30),
                                        0,
                                        ScreenUtil.getInstance()
                                            .setHeight(DP_20),
                                        0),
                                    decoration: BoxDecoration(
                                        color:
                                            Color.fromARGB(120, 255, 255, 255),
                                        borderRadius:
                                            BorderRadius.circular(25.0)),
                                    child: new Row(
                                      children: <Widget>[
                                        Icon(
                                          Icons.search,
                                          size: 25,
                                          color: Colors.white,
                                        ),
                                        Text(
                                          '搜索商品、品牌',
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(NORMAL_FONT_SIZE)),
                                        )
                                      ],
                                    ),
                                  ),
                                  onTap: () {
                                    Navigator.of(context).push(
                                        new MaterialPageRoute(
                                            builder: (context) {
                                      return new SearchGoodsListPage();
                                    }));
                                  },
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                        margin: EdgeInsets.fromLTRB(
                            0,
                            ScreenUtil.getInstance().setHeight(DP_160 - 20),
                            0,
                            0),
                        child: Column(
                          children: <Widget>[
                            Container(
                                padding: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    0,
                                    ScreenUtil.getInstance().setHeight(DP_20),
                                    0),
                                height: (MediaQuery.of(context).size.width -
                                        ScreenUtil.getInstance()
                                            .setHeight(DP_40)) /
                                    2.4,
                                child: bannerData == null
                                            ?SizedBox():Swiper(
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    return new ClipRRect(
                                      child: CachedNetworkImage(
                imageUrl:Api.ImgBaseUrl +
                                                bannerData[index].img,
                                        fit: BoxFit.fill,
                                      ),
                                      borderRadius: BorderRadius.circular(10.0),
                                    );
                                  },
                                  itemCount: bannerData.length,
                                  pagination: new SwiperPagination(
                                      builder: DotSwiperPaginationBuilder(
                                          color: Colors.grey,
                                          activeColor:mainColor,
                                          size: 7.0,
                                          activeSize: 7.0)),
                                  scrollDirection: Axis.horizontal,
                                  autoplay: true,
                                  onIndexChanged: (index) {
                                  },
                                  onTap: (index) {},
                                )),
                            Padding(
                              padding: EdgeInsets.fromLTRB(
                                  ScreenUtil.getInstance().setHeight(DP_20),
                                  ScreenUtil.getInstance().setHeight(DP_50),
                                  ScreenUtil.getInstance().setHeight(DP_20),
                                  0),
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    child: GestureDetector(
                                      onTap: () {
                                        Navigator.of(context).push(
                                            new MaterialPageRoute(
                                                builder: (context) {
                                          return new StudyClassPage();
                                        }));
                                      },
                                      child: Center(
                                        child: Column(
                                          children: <Widget>[
                                            Image.asset(
                                              "images/community_menu_a.png",
                                              scale: 1.5,
                                            ),
                                            Container(
                                              height: ScreenUtil.getInstance()
                                                  .setHeight(DP_15),
                                            ),
                                            Text('学堂',
                                                style: TextStyle(
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(
                                                            NORMAL_FONT_SIZE),
                                                    color: Colors.black87)),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                  Expanded(
                                    child: new GestureDetector(
                                      child: Center(
                                        child: Column(
                                          children: <Widget>[
                                            Image.asset(
                                              "images/community_menu_b.png",
                                              scale: 1.5,
                                            ),
                                            Container(
                                              height: ScreenUtil.getInstance()
                                                  .setHeight(DP_15),
                                            ),
                                            Text('素材',
                                                style: TextStyle(
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(
                                                            NORMAL_FONT_SIZE),
                                                    color: Colors.black87)),
                                          ],
                                        ),
                                      ),
                                      onTap: () {
                                        Navigator.of(context).push(
                                            new MaterialPageRoute(
                                                builder: (context) {
                                          return new MaterialCenterPage(
                                            type: 0,
                                          );
                                        }));
                                      },
                                    ),
                                  ),
                                  Expanded(
                                    child: GestureDetector(
                                      child: Center(
                                        child: Column(
                                          children: <Widget>[
                                            Image.asset(
                                              "images/community_menu_c.png",
                                              scale: 1.5,
                                            ),
                                            Container(
                                              height: ScreenUtil.getInstance()
                                                  .setHeight(DP_15),
                                            ),
                                            Text('社区',
                                                style: TextStyle(
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(
                                                            NORMAL_FONT_SIZE),
                                                    color: Colors.black87)),
                                          ],
                                        ),
                                      ),
                                      onTap: () {
                                        Navigator.of(context).push(
                                            new MaterialPageRoute(
                                                builder: (context) {
                                          return new MaterialCenterPage(
                                            type: 1,
                                          );
                                        }));
                                      },
                                    ),
                                  ),
                                  Expanded(
                                    child: GestureDetector(
                                      onTap: () {
                                        Navigator.of(context).push(
                                            new MaterialPageRoute(
                                                builder: (context) {
                                          return new PlayBillPage();
                                        }));
                                      },
                                      child: Center(
                                        child: Column(
                                          children: <Widget>[
                                            Image.asset(
                                              "images/community_menu_d.png",
                                              scale: 1.5,
                                            ),
                                            Container(
                                              height: ScreenUtil.getInstance()
                                                  .setHeight(DP_15),
                                            ),
                                            Text('海报',
                                                style: TextStyle(
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(
                                                            NORMAL_FONT_SIZE),
                                                    color: Colors.black87)),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            // Container(
                            //   width: double.infinity,
                            //   padding: EdgeInsets.fromLTRB(
                            //       ScreenUtil.getInstance().setHeight(DP_30),
                            //       ScreenUtil.getInstance().setHeight(DP_30),
                            //       0,
                            //       0),
                            //   child: Text(
                            //     '产品素材',
                            //     style: TextStyle(
                            //         fontSize: ScreenUtil.getInstance()
                            //             .setSp(NORMAL_FONT_SIZE),
                            //         color: Colors.black),
                            //     maxLines: 1,
                            //     overflow: TextOverflow.ellipsis,
                            //   ),
                            // ),
                          ],
                        ))
                  ],
                );
              }
              return Container(
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setHeight(DP_20),
                    ScreenUtil.getInstance().setHeight(DP_20),
                    ScreenUtil.getInstance().setHeight(DP_30),
                    0),
                child: ListView.builder(
                    physics: NeverScrollableScrollPhysics(),
                    padding: EdgeInsets.all(0),
                    shrinkWrap: true,
                    itemBuilder: _renderRow,
                    itemCount: dataList.length),
              );
            },
            itemCount: 2,
          ),
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setHeight(DP_20),
          0,
          ScreenUtil.getInstance().setHeight(DP_20),
          ScreenUtil.getInstance().setHeight(DP_20)),
      decoration: BoxDecoration(
          color: white,
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10))),
      child: Material(
        borderRadius:
            BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10)),
        color: white,
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.only(
                  topRight: Radius.circular(
                      ScreenUtil.getInstance().setHeight(DP_10)),
                  topLeft: Radius.circular(
                      ScreenUtil.getInstance().setHeight(DP_10))),
              child: dataList[index].img == ""
                  ? Image.asset('images/app_icon.png',
                      width: MediaQuery.of(context).size.width -
                          ScreenUtil.getInstance().setHeight(DP_40),
                      fit: BoxFit.cover,
                      height: (MediaQuery.of(context).size.width -
                              ScreenUtil.getInstance().setHeight(DP_40)) /
                          2)
                  : CachedNetworkImage(
                imageUrl:Api.ImgBaseUrl + dataList[index].img,
                      width: MediaQuery.of(context).size.width -
                          ScreenUtil.getInstance().setHeight(DP_40),
                      fit: BoxFit.fill,
                      height: (MediaQuery.of(context).size.width -
                              ScreenUtil.getInstance().setHeight(DP_40)) /
                          2),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_8)),
              child: Text(
                dataList[index].title,
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                    color: black),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_15),
                  0,
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_15)),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  Text('金牌讲师：' + dataList[index].author,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                          color: mainColor)),
                ],
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_15),
                  0,
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_15)),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  // SizedBox(
                  //   width: 18 * 4.toDouble() + 12,
                  //   child: Stack(
                  //     alignment: AlignmentDirectional.topStart,
                  //     children: <Widget>[
                  //       ClipOval(
                  //         child: CachedNetworkImage(
                // imageUrl:
                  //             'https://cdn2.jianshu.io/assets/default_avatar/14-0651acff782e7a18653d7530d6b27661.jpg',
                  //             width: 30,
                  //             height: 30),
                  //       ),
                  //       Positioned(
                  //         left: 18,
                  //         child: ClipOval(
                  //           child: CachedNetworkImage(
                // imageUrl:
                  //               'https://cdn2.jianshu.io/assets/default_avatar/14-0651acff782e7a18653d7530d6b27661.jpg',
                  //               width: 30,
                  //               height: 30),
                  //         ),
                  //       ),
                  //       Positioned(
                  //         left: 36,
                  //         child: ClipOval(
                  //           child: CachedNetworkImage(
                // imageUrl:
                  //               'https://cdn2.jianshu.io/assets/default_avatar/14-0651acff782e7a18653d7530d6b27661.jpg',
                  //               width: 30,
                  //               height: 30),
                  //         ),
                  //       ),
                  //       Positioned(
                  //         left: 54,
                  //         child: ClipOval(
                  //           child: CachedNetworkImage(
                // imageUrl:
                  //               'https://cdn2.jianshu.io/assets/default_avatar/14-0651acff782e7a18653d7530d6b27661.jpg',
                  //               width: 30,
                  //               height: 30),
                  //         ),
                  //       ),
                  //     ],
                  //   ),
                  // ),
                  // Container(width: ScreenUtil.getInstance().setHeight(DP_15)),
                  Text(dataList[index].clicknum + '人已学',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                          color: Colors.black54)),
                  Expanded(
                    child: Center(),
                  ),
                  new Container(
                    height: ScreenUtil.getInstance().setWidth(DP_50),
                    decoration: new BoxDecoration(
                        border: Border.all(color: mainColor, width: 1),
                        borderRadius: BorderRadius.circular(2)),
                    child: new FlatButton(
                      child: new Padding(
                        padding: EdgeInsets.all(0.0),
                        child: new Text(
                          "去学习",
                          style: new TextStyle(
                              color: mainColor,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE)),
                        ),
                      ),
                      onPressed: () {
                        Navigator.of(context)
                            .push(MaterialPageRoute(builder: (context) {
                          return new ArticleDetailPage(
                            article_id: dataList[index].article_id,
                          );
                        }));
                      },
                    ),
                  )
                ],
              ),
            )
          ],
        ),
        elevation: 1,
      ),
    );
  }
}
